﻿// ***********************************************************************
// Assembly         : INNOVACALL.Framework.Common
// Author           : LJO+01 (Laurent Jordi)
// Created          : 06-05-2013
// Last Modified By : LJO+01 (Laurent Jordi)
// Last Modified On : 06-05-2013
// ***********************************************************************
// <copyright file="StringsExtensions.cs" company="Copyright © Innovacall 2011">
//     Copyright (c) Copyright © Innovacall 2011. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using INNOVACALL.Framework.Common.Properties;
using System.Text.RegularExpressions;

namespace INNOVACALL.Framework.Common.Extensions
{
    /// <summary>
    /// All extensions for strings
    /// </summary>
    public static class StringExtension
    {
        /// <summary>
        /// Read entire file content en return it in a byte[]
        /// </summary>
        /// <param name="fileName">Just the filename</param>
        /// <param name="filePath">Path to file</param>
        /// <returns>System.Byte[][].</returns>
        /// <exception cref="System.IO.FileNotFoundException"></exception>
        public static byte[] GetFileData(this string fileName, string filePath)
        {
            var fullFilePath = Path.Combine(filePath, fileName);
            if (!File.Exists(fullFilePath))
                throw new FileNotFoundException(Resources.ErrMsg_Extensions_Strings_GetFileData_FileNotFound, fullFilePath);
            return File.ReadAllBytes(fullFilePath);
        }
        /// <summary>
        /// Deserializes the specified xmlstring.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlstring">The xmlstring.</param>
        /// <returns>``0.</returns>
        public static T Deserialize<T>(this string xmlstring) where T : class
        {
            XmlSerializer aXml = new XmlSerializer(typeof(T), "");
            MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xmlstring));
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
            return aXml.Deserialize(memoryStream) as T;
        }

        /// <summary>
        /// Strings to UT f8 byte array.
        /// </summary>
        /// <param name="pXmlString">The p XML string.</param>
        /// <returns>Byte[][].</returns>
        public static Byte[] StringToUTF8ByteArray(this string pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }


        /// <summary>
        /// Automatics the authentication f8 string.
        /// </summary>
        /// <param name="toConvert">The automatic convert.</param>
        /// <returns>System.String.</returns>
        public static string ToUTF8String(this string toConvert)
        {
            string toReturn = string.Empty;
            byte[] bytes = toConvert.StringToUTF8ByteArray();
            toReturn = Encoding.UTF8.GetString(bytes); 
            return toReturn;
        }
        private class Utf8StringWriter : StringWriter
        {
            public override Encoding Encoding { get { return Encoding.UTF8; } }
        }
        /// <summary>
        /// Encodes the SH a1.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns>System.String.</returns>
        public static string EncodeSHA1(this string text)
        {
            System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();

            byte[] buffer = enc.GetBytes(text);
            SHA1CryptoServiceProvider cryptoTransformSHA1 =
            new SHA1CryptoServiceProvider();
            string hash = BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "");
            return hash;
        }

        /// <summary>
        /// Encodes the MD5.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns>System.String.</returns>
        public static string EncodeMd5(this string input)
        {
            MD5 md5Hasher = MD5.Create();

            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }

        /// <summary>
        /// Trims the AL.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns>System.String.</returns>
        public static string TrimAL(this string input)
        {
            if (string.IsNullOrEmpty(input))
                return string.Empty;

            string toReturn;
            toReturn = input.Trim();
            toReturn = (string.IsNullOrEmpty(toReturn) || string.IsNullOrWhiteSpace(toReturn) ? " " : toReturn);

            //toReturn = Regex.Replace(toReturn, "[^0-9a-zA-Z]+", "");
            return toReturn;
        }

        /// <summary>
        /// Uns the map path.
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <returns>System.String.</returns>
        public static string UnMapPath(this string folder)
        {
            string tmp;
            string strRoot;
            strRoot = HttpContext.Current.Server.MapPath("/");
            tmp = folder.ToLower().Replace(strRoot.ToLower(), "");
            tmp = tmp.Replace(@"\", @"/");
            return tmp;
        }


        /// <summary>
        /// Extracts the text from HTML.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <returns>System.String.</returns>
        public static string ExtractTextFromHTML(this string source)
        {
            Regex regex = new Regex("(<.*?>\\s*)+", RegexOptions.Singleline);

            // replace all html tags (and consequtive whitespaces) by spaces
            // trim the first and last space

            string resultText = regex.Replace(source, " ").Trim();

            return resultText;
        }

        /// <summary>
        /// Remove HTML tags from string using char array. OBSOLETE
        /// </summary>
        /// <param name="source">The source.</param>
        /// <returns>System.String.</returns>
        public static string StripTagsCharArray(this string source)
        {
            if (String.IsNullOrEmpty(source)) return null;
            char[] array = new char[source.Length];
            int arrayIndex = 0;
            bool inside = false;

            for (int i = 0; i < source.Length; i++)
            {
                char let = source[i];
                if (let == '<')
                {
                    inside = true;
                    continue;
                }
                if (let == '>')
                {
                    inside = false;
                    continue;
                }
                if (!inside)
                {
                    array[arrayIndex] = let;
                    arrayIndex++;
                    if (source[i + 1] == '<')
                    {
                        array[arrayIndex] = ' ';
                        arrayIndex++;
                    }
                }
            }
            return new string(array, 0, arrayIndex);
        }
        /// <summary>
        /// Renvoyer le contenu d'un fichier passé en paramètre sous la forme d'une chaine de caractère
        /// </summary>
        /// <param name="fileName">Chemin complet du fichier</param>
        /// <returns>Contenu du fichier</returns>
        public static string ReadContentFile(this string fileName)
        {
            try
            {
                string content = default(string);
                using (FileStream file = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    using (var reader = new StreamReader(file))
                    {
                        content = reader.ReadToEnd();
                    }
                }
                return content;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// Ensures the path exists.
        /// </summary>
        /// <param name="path">The path.</param>
        public static void EnsurePathExists(this string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }
    }
}
